<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '新增自选',
  },
}
</route>
<template>
  <PageLayout :navbarShow="false">
    <scroll-view class="wrap" scroll-y>
      <wd-search
        v-model="searchStr"
        @clear="change"
        @cancel="cancel"
        @change="change"
        :maxlength="10"
      />

      <view v-if="showList" style="background-color: #fff">
        <view
          v-for="i in searchList"
          :key="i"
          style="border-bottom: 1px solid #f2f2f2; padding: 20rpx 20rpx"
        >
          <wd-row>
            <wd-col :span="16">
              <view @click="onClickItemName(i)" style="margin-bottom: 5px; font-weight: 500">
                {{ i.name }}
              </view>
              <view style="font-size: 22rpx; color: #696969">
                <text style="margin-right: 5px">{{ i.code }}</text>
                <text>{{ i.type }}</text>
              </view>
            </wd-col>
            <wd-col :span="5">
              <view
                style="text-align: right; margin-bottom: 5px"
                :style="{ color: i.syl_1n != null && i.syl_1n > 0 ? 'red' : 'green' }"
              >
                {{
                  i.syl_1n == null
                    ? '--'
                    : i.syl_1n > 0
                      ? '+' + i.syl_1n.toFixed(2)
                      : i.syl_1n.toFixed(2)
                }}{{ i.syl_1n == null ? '' : '%' }}
              </view>
              <view style="text-align: right; font-size: 22rpx; color: #696969">近1年</view>
            </wd-col>
            <wd-col :span="3">
              <view
                @click="onClickSelect(i)"
                style="
                  text-align: center;
                  width: 40rpx;
                  height: 40rpx;
                  background-color: blue;
                  margin: 0 auto;
                  color: #fff;
                  margin-top: 12rpx;
                "
                :style="{
                  backgroundColor: i.opt_id == null ? '#d0e8ff' : '#ccc',
                  color: i.opt_id == null ? '#0083ff' : '#fff',
                }"
              >
                <wd-icon name="add" size="20rpx" v-if="i.opt_id == null"></wd-icon>
                <wd-icon name="decrease" size="20rpx" v-else></wd-icon>
              </view>
            </wd-col>
          </wd-row>
        </view>
        <!--查看更多-->
        <view
          v-if="totalPages > pageNo && searchList.length > 0"
          style="text-align: center; padding: 20rpx 0px"
          @click="onClickMore"
        >
          查看更多
        </view>
      </view>

      <view v-else style="padding: 20rpx">
        <!--搜索历史-->
        <view v-if="historySearchArr.length > 0">
          <view style="display: flex; justify-content: space-between">
            <view>搜索历史</view>
            <view><wd-icon name="delete" @click="onClickClearHistory"></wd-icon></view>
          </view>
          <view style="display: flex; margin-top: 20rpx; margin-bottom: 20rpx; flex-wrap: wrap">
            <view
              v-for="i in historySearchArr"
              :key="i"
              style="
                background-color: #edf8fd;
                padding: 12rpx 20rpx;
                border-radius: 8rpx;
                margin-right: 20rpx;
                font-size: 20rpx;
                margin-bottom: 20rpx;
              "
              @click="onClickHistory(i)"
            >
              {{ i.name }}
            </view>
          </view>
        </view>
        <view>
          <view>热搜榜单</view>
          <!--骨架屏-->
          <view v-if="showLoadingView">
            <wd-skeleton v-for="i in 2" :key="i" theme="paragraph" style="margin-bottom: 10rpx" />
          </view>

          <!--空数据提示-->
          <wd-status-tip
            image="../../static/content.png"
            tip="暂无榜单数据 "
            v-else-if="!showLoadingView && hotSearchDataList.length == 0"
          />
          <view
            style="
              width: 96%;
              background-color: #fff;
              border-radius: 10rpx;
              padding: 20rpx;
              margin: 10rpx auto;
            "
            v-else
          >
            <view
              v-for="(data, index) in hotSearchDataList"
              :key="index"
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-size: 22rpx;
                margin-bottom: 10rpx;
              "
            >
              <view style="display: flex; align-items: center">
                <view
                  style="padding: 8rpx 16rpx; font-size: 18rpx; border-radius: 4rpx; color: #fff"
                  :style="{
                    backgroundColor:
                      index === 0
                        ? '#fd696c'
                        : index === 1
                          ? '#fd9747'
                          : index === 2
                            ? '#fdc780'
                            : '#cccccc',
                  }"
                >
                  {{ index + 1 }}
                </view>
                <view style="margin-left: 10rpx">{{ data.name }}</view>
              </view>
              <view style="color: #8a8a8a">{{ data.total }}</view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </PageLayout>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { http } from '@/utils/http'
import { useMessage } from 'wot-design-uni'

defineOptions({
  name: 'addChoose',
  options: {
    styleIsolation: 'shared',
  },
})
// 搜索条件
const searchStr = ref('')
// 每页显示数量
const pageSize = ref(10)
// 当前页码
const pageNo = ref(1)
// 是否显示查询列表
const showList = ref(false)
// 查询列表
const searchList = ref([])
// 总页码
const totalPages = ref(0)
// 搜索历史
const historySearchArr = ref([])
const message = useMessage()
// 热搜数据
const hotSearchDataList = ref([])
// 显示loading
const showLoadingView = ref(true)

// 点击历史
const onClickHistory = (data) => {
  searchStr.value = data.name
  change()
}

// 点击跳转到
const onClickItemName = (data) => {
  saveHistory(data)

  uni.navigateTo({
    url:
      '/pages/detail/detail?code=' +
      data.code +
      '&fundId=' +
      data.id +
      '&optId=' +
      data.opt_id +
      '&lineType=' +
      (data.opt_id == null ? 'default' : 'optional'),
  })
}

// 保存历史数据
const saveHistory = (data) => {
  http
    .post('/sys/fund/search/history/create', {
      searchStr: searchStr.value,
      code: data.code,
      fundId: data.id,
      name: data.name,
    })
    .then((res: any) => {
      if (res.success) {
        console.log('创建成功')
        loadHistoryList()
      }
    })
}

// 清空历史
const onClickClearHistory = () => {
  message
    .confirm({
      msg: '是否清空历史搜索数据？',
      title: '提示',
    })
    .then(() => {
      http.post('/sys/fund/search/history/clear').then((res: any) => {
        if (res.success) {
          console.log('清空成功')
        }
      })
    })
    .catch(() => {
      console.log('点击了取消按钮')
    })
}

// 加载搜索的内容
const loadSearchList = () => {
  http
    .get('/sys/fund/library/page', {
      name: searchStr.value,
      pageNo: pageNo.value,
      pageSize: pageSize.value,
    })
    .then((res: any) => {
      if (res.success) {
        // 结果集
        const result = res.result
        // 列表
        const records = result.records
        // 设置搜索结果
        if (pageNo.value === 1) {
          searchList.value = records
        } else {
          records.forEach((item) => {
            searchList.value.push(item)
          })
        }
        // 设置总页码
        totalPages.value = result.pages
      }
    })
}

// 点击查看更多
const onClickMore = () => {
  if (pageNo.value < totalPages.value) {
    pageNo.value += 1
    loadSearchList()
  }
}

// 搜索条件改变
const change = () => {
  if (searchStr.value.length > 0) {
    // 内容清空
    searchList.value = []
    // 显示搜索条件
    showList.value = true
    // 开始搜索
    loadSearchList()
  } else {
    // 不显示搜索条件
    showList.value = false
    // 数据清空
    searchList.value = []
  }
}

// 取消
const cancel = () => {
  uni.navigateBack()
}

// 点击自选
const onClickSelect = (item) => {
  saveHistory(item)

  if (item.opt_id == null) {
    http.post('/sys/fund/optional/add', { fundId: item.id }).then((res: any) => {
      if (res.success) {
        const result = res.result
        item.opt_id = result.id
        uni.showToast({
          title: '添加成功',
          duration: 2000,
        })
      }
    })
  } else {
    http.post('/sys/fund/optional/delete', { id: item.opt_id }).then((res: any) => {
      if (res.success) {
        item.opt_id = null
        uni.showToast({
          title: '取消成功',
          duration: 2000,
        })
      }
    })
  }
}

// 加载热搜榜单
const loadHotSearch = () => {
  http.get('/sys/fund/search/history/hotSearch').then((res: any) => {
    if (res.success) {
      const result = res.result
      hotSearchDataList.value = result
    }
  })
}

// 加载历史数据
const loadHistoryList = () => {
  showLoadingView.value = true
  http.get('/sys/fund/search/history/list').then((res: any) => {
    if (res.success) {
      historySearchArr.value = res.result
      showLoadingView.value = false
    }
  })
}
onLoad(() => {
  loadHistoryList()
  // 加载热搜数据
  loadHotSearch()
})
</script>

<style lang="scss" scoped>
.wrap {
  background: linear-gradient(to bottom, #daf0fe, #f9fbfb);
}
</style>
